﻿#include "parametersetdialog.h"
#include "ui_parametersetdialog.h"

ParameterSetDialog::ParameterSetDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ParameterSetDialog),
    m_itemPerPage(8)
{
    ui->setupUi(this);
    setWindowFlags (Qt::Window | Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);

    this->move(0+g_mainWidgetPos.x(),0+g_mainWidgetPos.y());
    m_setedFlag = 0;
    m_rootCurPage = 0;

    //获取网卡ID
    m_networkCardID.clear();
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    if(interfaces.size() == 1)
    {
        QNetworkInterface item = interfaces.at(0);
        m_networkCardID = item.hardwareAddress();
    }
    else
    {
        int nCnt = interfaces.count();
        for(int i = 0; i < nCnt; i++)
        {
            //QNetworkInterface item = interfaces.at(i);
            //m_networkCardID = item.hardwareAddress();

            // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
            if(interfaces[i].flags().testFlag(QNetworkInterface::IsUp) &&
                    interfaces[i].flags().testFlag(QNetworkInterface::IsRunning) &&
                    !interfaces[i].flags().testFlag(QNetworkInterface::IsLoopBack))
            {
                m_networkCardID = interfaces[i].hardwareAddress();
                qDebug()<<m_networkCardID;
                break;
            }
        }
    }

    initData();
    initControl();
    refreshUi();
}

ParameterSetDialog::~ParameterSetDialog()
{
    delete ui;
}

//初始化窗体控件，包括位置、尺寸、样式
void ParameterSetDialog::initControl()
{
    m_itemBtnList.clear();
    m_itemBtnList.append(ui->button1);
    m_itemBtnList.append(ui->button2);
    m_itemBtnList.append(ui->button3);
    m_itemBtnList.append(ui->button4);
    m_itemBtnList.append(ui->button5);

    ui->button6->setVisible(true);//显示
    ui->button7->setVisible(true);
    ui->button8->setVisible(true);
    m_itemBtnList.append(ui->button6);
    m_itemBtnList.append(ui->button7);
    m_itemBtnList.append(ui->button8);

    ui->button9->setVisible(false);
    ui->button10->setVisible(false);
    ui->button11->setVisible(false);
    ui->button12->setVisible(false);

    //根据不同分辨率设置控件的位置和尺寸
    initResolution();
    initControlStyle();//初始化窗体控件样式
}


//初始化窗体控件为任意分辨率
void ParameterSetDialog::initResolution()
{
    double factoryX = getFactoryX();
    double factoryY = getFactoryY();

    this->resize(GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    ui->frameBack->setGeometry(0*factoryX,0*factoryY,GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    ui->buttonTypeLogo->setGeometry(GLB_EDGE_WIGHT*factoryX,GLB_EDGE_HEIGHT*factoryY,GLB_LICON_SIZE*factoryX,GLB_LICON_SIZE*factoryY);
    ui->labelMainTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT)*factoryX,GLB_EDGE_HEIGHT*factoryY,
                                    (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT*2))*factoryX,GLB_TEXT_L_HEIGHT*factoryY);
    ui->labelSubTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT)*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_TEXT_HEIGHT)*factoryY,
                                   (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT*2))*factoryX,GLB_TEXT_HEIGHT*factoryY);

    ui->frameRightUp->setGeometry(0*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_MICON_SIZE)*factoryY,GLB_SCR_WIGHT*factoryX,GLB_MICON_SIZE*factoryY);
    ui->buttonParaRestore->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_MICON_SIZE))*factoryX,0*factoryY,GLB_MICON_SIZE*factoryX,GLB_MICON_SIZE*factoryY);
    ui->buttonReturn->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*1+GLB_MICON_SIZE*2))*factoryX,0*factoryY,GLB_MICON_SIZE*factoryX,GLB_MICON_SIZE*factoryY);

    //内容的位置
    QRect rectName(GLB_TAB_WIGHT*factoryX,GLB_ICON_TEXT*factoryY,(GLB_PARA_WIGHT-GLB_TAB_WIGHT*2)*factoryX,GLB_LBUT_HEIGHT*factoryY);
    QRect rectValue(GLB_TAB_WIGHT*factoryX,GLB_ICON_TEXT*factoryY,(GLB_PARA_WIGHT-GLB_TAB_WIGHT*2)*factoryX,GLB_LBUT_HEIGHT*factoryY);
    for(int i = 0; i < m_itemPerPage; i++)//白色按下的效果
    {
        m_itemBtnList[i]->setGeometry(GLB_PARA_LEFT*factoryX,(GLB_PARA_TOP + i * GLB_PARA_HEIGHT +3)*factoryY,GLB_PARA_WIGHT*factoryX,(GLB_PARA_HEIGHT-3)*factoryY);
        m_itemBtnList[i]->initLeftNameRightValue(rectName,rectValue,1);
    }

    ui->labelPage->setGeometry(GLB_EDGE_WIGHT*factoryX,(GLB_SCR_HEIGHT-GLB_TEXT_HEIGHT-GLB_EDGE_WIGHT)*factoryY, (GLB_SCR_WIGHT/3)*factoryX,GLB_TEXT_HEIGHT*factoryY);

    ui->framePageBtn->setGeometry(0*factoryX,(GLB_SCR_HEIGHT-GLB_LBUT_HEIGHT-GLB_EDGE_WIGHT)*factoryY,GLB_SCR_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonPgUp->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*3+GLB_LBUT_WIGHT*4))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonPgDn->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*2+GLB_LBUT_WIGHT*3))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonOk->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*1+GLB_LBUT_WIGHT*2))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonCancel->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*0+GLB_LBUT_WIGHT*1))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
}

//初始化窗体控件样式
void ParameterSetDialog::initControlStyle()
{
    SetStyle setControlStyle;
    setControlStyle.setUiName(this->objectName());

    //背景图
    QString frameBackImgPath = setControlStyle.getSharedStyleSheet();
    ui->frameBack->setStyleSheet(frameBackImgPath);
    ui->labelMainTitle->setFont(fontSize_L());
    ui->labelMainTitle->setStyleSheet(titleTextColour());
    ui->labelSubTitle->setFont(fontSize_M());
    ui->labelSubTitle->setStyleSheet(noteTextColour());
    ui->labelPage->setFont(fontSize_M());
    ui->labelPage->setStyleSheet(commonTextColour());
    //右上方
    ui->frameRightUp->setStyleSheet(transparentStyle());
    ui->buttonParaRestore->setStyleSheet(backIconStyle());;
    ui->buttonParaRestore->setTopImage(setControlStyle.getTopStyleSheet(ui->buttonParaRestore->objectName()));
    ui->buttonReturn->setStyleSheet(backIconStyle());;
    ui->buttonReturn->setTopImage(setControlStyle.getTopStyleSheet(ui->buttonReturn->objectName()));

    //条目
    for(int i = 0; i < m_itemPerPage; i++)
    {
        m_itemBtnList[i]->setLabelFont(fontSize_M());
    //    m_itemBtnList[i]->setStyleSheet(commonTextColour());
    }

    //四个按钮样式表一样
    ui->buttonPgUp->setStyleSheet(confirmIconStyle());
    ui->buttonPgUp->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgUp->objectName()),12);

    ui->buttonPgDn->setStyleSheet(confirmIconStyle());
    ui->buttonPgDn->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgDn->objectName()),12);

    ui->buttonOk->setStyleSheet(confirmIconStyle());
    ui->buttonOk->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonOk->objectName()),12);

    ui->buttonCancel->setStyleSheet(confirmIconStyle());
    ui->buttonCancel->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonCancel->objectName()),12);
}

void ParameterSetDialog::refreshUi()
{        
    ui->buttonOk->setVisible(true);//再进入界面时,刷新界面确认按钮就显示
    ui->labelRepetitions->setVisible(false);//先隐藏

    if(m_paraType == PARA_TYPE_HMICONFIGURATION)//等于界面配置
    {
        refreshProductType();//刷新产品类型
    }

    if (m_itemList.size() <= 0)//参数列表
    {
        for (int i = 0; i < m_itemPerPage; i++)
        {
            m_itemBtnList.at(i)->hide();
        }
        ui->labelPage->setText("PageNum: 0/0");
        ui->buttonPgUp->setEnabled(false);
        ui->buttonPgDn->setEnabled(false);
        ui->buttonOk->setEnabled(false);
        ui->frameRightUp->setVisible(false);

        return;//下边的代码不执行
    }

    if(m_itemPerPage <= 0)
    {
        return;
    }

    ui->buttonOk->setEnabled(true);
    QString split1 = ":";
    QString split2 = ";";
    QString str;

    //-----------
    int itemNum, pageNums;
    itemNum = m_itemList.size();//列表总个数
    pageNums = (itemNum+m_itemPerPage-1) / m_itemPerPage;//一共有的页数

    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        if (m_rootCurPage > pageNums)                 // 当前页
        {
            m_rootCurPage = pageNums;
        }
        if (m_rootCurPage <= 1)
        {
            m_rootCurPage = 1;
        }

    }
    else
    {
        if (m_curPage > pageNums)                 // 当前页
        {
            m_curPage = pageNums;
        }
        if (m_curPage <= 1)
        {
            m_curPage = 1;
        }
    }

    // 条目信息
    int i, itemidx;
    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        itemidx = (m_rootCurPage-1) * m_itemPerPage;
    }
    else
    {
        itemidx = (m_curPage-1) * m_itemPerPage;
    }


    for (i = 0; i < m_itemPerPage; i++)
    {
        if (itemidx < m_itemList.size())
        {
            const ParaItem & item = m_itemList.at(itemidx);

            if (item.readonly != 0) // 只读，不能设置
            {
                m_itemBtnList.at(i)->show();
                m_itemBtnList.at(i)->setEnabled(false);
            }
            else
            {
                //超级用户选择工作参数开关型后回到遍历设置会显示开关，以下代码隐藏开关
                if(item.valueType == PARA_VALUE_TYPE_CLICK)
                {
                    m_itemBtnList.at(i)->setLabelValueImage("");
                }
                m_itemBtnList.at(i)->show();
                m_itemBtnList.at(i)->setEnabled(true);
            }

            m_itemBtnList.at(i)->setLabelName(item.paraName);

            if (item.valueType == PARA_VALUE_TYPE_INT)    // = 1, 数字输入型
            {
                str = getValueStr(item.value, item.afterPoint);//显示的是默认参数
                str += " " + item.unitStr;
                //    qDebug()<< item.value << item.afterpoint << item.unitstr;
                m_itemBtnList.at(i)->setLabelValue(str);//设置参数显示的值，没连上就显示的默认参数
                m_itemBtnList.at(i)->show();
            }
            else if (item.valueType == PARA_VALUE_TYPE_SW)   // = 2, 开关选择型
            {
                SetStyle setControlStyle;
                setControlStyle.setUiName(this->objectName());

                QString path;
                path = setControlStyle.getBottomStyleSheet1("");

                if (item.value != 0)//打开
                {
                    path += "switchOn_logo.png";
                }
                else
                {
                    path += "switchOff_logo.png";
                }

                m_itemBtnList.at(i)->setLabelValueImage(path);
            }
            else if (item.valueType == PARA_VALUE_TYPE_LIST)   // = 3, 列表选择型
            {
                QStringList vallist;
                if(item.selList.indexOf(split1) == -1)
                {
                    // 没找到 二级分割
                    vallist = item.selList.split(split2, QString::SkipEmptyParts);
                    if (vallist.size() <= 0)
                    {
                        str = "";
                    }
                    else
                    {
                        int selIdx = item.selIdx;
                        if (selIdx < 0)
                        {
                            selIdx = 0;
                        }
                        if (selIdx >= vallist.size())
                        {
                            selIdx = vallist.size() - 1;
                        }
                        str = vallist.at(selIdx);
                    }
                }
                else
                {
                    // 二级分割
                    vallist = item.selList.split(split2, QString::SkipEmptyParts);
                    if (vallist.size() <= 0)
                    {
                        str = "";
                    }
                    else
                    {
                        int miniIndex = vallist.first().split(split1, QString::SkipEmptyParts).at(1).toInt();
                        int maxIndex = vallist.last().split(split1, QString::SkipEmptyParts).at(1).toInt();

                        //int selIdx = item.value;
                        int selIdx = item.selIdx;
                        if (selIdx < miniIndex)
                        {
                            selIdx = miniIndex;
                        }
                        if (selIdx >= maxIndex)
                        {
                            selIdx = maxIndex;
                        }
                        for (int var = 0; var < vallist.size(); ++var)
                        {
                            QStringList sublist = vallist.at(var).split(split1, QString::SkipEmptyParts);
                            if(sublist.at(1).toInt() == selIdx)
                            {
                                str = sublist.at(0);
                            }
                        }
                    }
                }
                if((m_paraType == PARA_TYPE_PATTERN && item.indexInPara == SET_ROTATESTYLE) ||	//旋转式样
                        (m_paraType == PARA_TYPE_PATTERN && item.indexInPara == SET_HORIZONTALSTYLE) ||	//水平翻转
                        (m_paraType == PARA_TYPE_PATTERN && item.indexInPara == SET_VERTICALSTYLE))	//垂直翻转
                {
                    //旋转式样加载P的图片
                    SetStyle setControlStyle;
                    setControlStyle.setUiName(this->objectName());

                    QString path = setControlStyle.getSharedBottomStyleSheet("") + str + "_logo.png";
                    m_itemBtnList.at(i)->setLabelValueImage(path);
                }
                else
                {
                    m_itemBtnList.at(i)->setLabelValue(str);
                }
            }
            else if (item.valueType == PARA_VALUE_TYPE_STRINPUT)   // = 4, 字符串输入型
            {
                str = item.valueStr;
                m_itemBtnList.at(i)->setLabelValue(str);
                m_itemBtnList.at(i)->show();
            }
            else    //  = 0, 无值
            {
                m_itemBtnList.at(i)->setLabelValue("");
            }
            itemidx++;
        }
        else
        {
            m_itemBtnList.at(i)->setEnabled(false);
            m_itemBtnList.at(i)->hide();
        }
    }

    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        // 超级用户界面按钮
        if (m_rootCurPage <= 1)
        {
            ui->buttonPgUp->setEnabled(false);
        }
        else
        {
            ui->buttonPgUp->setEnabled(true);
        }

        if (m_rootCurPage >= pageNums)
        {
            ui->buttonPgDn->setEnabled(false);
        }
        else
        {
            ui->buttonPgDn->setEnabled(true);
        }
    }
    else
    {
        // 按钮
        if (m_curPage <= 1)
        {
            ui->buttonPgUp->setEnabled(false);
        }
        else
        {
            ui->buttonPgUp->setEnabled(true);
        }

        if (m_curPage >= pageNums)
        {
            ui->buttonPgDn->setEnabled(false);
        }
        else
        {
            ui->buttonPgDn->setEnabled(true);
        }
    }

    // 页信息
    QString strPage;
    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        strPage = tr("pageNum: ") + QString("%1/%2").arg(m_rootCurPage).arg(pageNums);//页数:
    }
    else
    {
        strPage = tr("pageNum: ") + QString("%1/%2").arg(m_curPage).arg(pageNums);//页数:
    }

    ui->labelPage->setText(strPage);

    if(m_paraType == PARA_TYPE_ROOT)
    {
        ui->buttonOk->setEnabled(false);
        //ui->buttonOk->setEnabled(true);//增加了界面调试模式,超级用户界面按钮可用
    }

    if(m_paraType == PARA_TYPE_MACH ||
            m_paraType == PARA_TYPE_WORK)//机头板参数或换色板参数或机器参数或工作参数(机器参数或工作参数为超级用户目录下的)
    {
        ui->frameRightUp->setVisible(true);
        ui->buttonParaRestore->setVisible(true);//恢复默认参数按钮
        ui->buttonReturn->setVisible(true);//返回上一级按钮或重置反复绣次数
    }
    else if( m_paraType == PARA_TYPE_HMICONFIGURATION||//界面配置
             m_paraType == PARA_TYPE_IOTCONFIGURATION //物联网配置
              )
    {
        ui->frameRightUp->setVisible(true);
        ui->buttonParaRestore->setVisible(false);
        ui->buttonReturn->setVisible(true);//返回上一级按钮
    }
    else
    {
        ui->frameRightUp->setVisible(false);
    }
    //超级用户界面配置
    if(m_paraType == PARA_TYPE_HMICONFIGURATION)
    {
        ui->buttonOk->setEnabled(true);      
    }
}

QString ParameterSetDialog::getValueStr(int64_t val, int afterpoint)
{
    QString str;
    double value = val;
    if (afterpoint <= 0)
    {
        str.sprintf("%.0f", value);
    }
    else if (afterpoint == 1)
    {
        value /= 10;
        str.sprintf("%.1f", value);
    }
    else if (afterpoint == 2)
    {
        value /= 100;
        str.sprintf("%.2f", value);
    }
    else if (afterpoint == 3)
    {
        value /= 1000;
        str.sprintf("%.3f", value);
    }
    else // if (afterpoint >= 4)
    {
        value /= 10000;
        str.sprintf("%.4f", value);
    }
    return str;
}

void ParameterSetDialog::changeValue(int buttenidx)
{
#if(0)
    //等于机器参数或工作参数
    if(((m_paraType & PARA_TYPE_MACH) == PARA_TYPE_MACH) ||
            ((m_paraType & PARA_TYPE_WORK) == PARA_TYPE_WORK))
    {
        if(g_emUser != repair)//权限不够先登录
        {
            emit siUserLogin(repair);
            if(g_emUser != repair)//发送登录信号后，权限如果还没改变就返回
                return;
        }
    }
#endif

    QString split1 = ":";
    QString split2 = ";";

    if (buttenidx < 0 || buttenidx >= m_itemPerPage)
    {
        return ;
    }

    int itemidx;
    int selIdx = 0;
    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        itemidx = (m_rootCurPage-1) * m_itemPerPage;
    }
    else
    {
        itemidx = (m_curPage-1) * m_itemPerPage;
    }

    itemidx += buttenidx;

    if (itemidx < m_itemList.size())
    {
        int chgflag = 0;
        s32 newvalue;
        QString newStrValue;
        const ParaItem & item = m_itemList.at(itemidx);
        newvalue = item.value;//等于这个列表现在的值
        newStrValue = item.valueStr;

        if (item.valueType == PARA_VALUE_TYPE_INT)    // 数字型
        {
            int rslt;
            NumerInputDialog ndlg(this);
            ndlg.setTitleStr(item.paraName);
            ndlg.setUnitStr(item.unitStr);
            ndlg.setValueAndRange(item.value, item.minVal, item.maxVal, item.afterPoint);
            rslt = ndlg.exec();

            if (rslt == 1)//点了确认按钮
            {
                s32 val = ndlg.getValue();
                if (val != newvalue)//更改后的值不等于之前存的值
                {

                    if(getItemValue(SET_EQUAL) == 1){ //等比缩放 调整x或y之后自动调整另一个的比例
                        s32 x1 = getItemValue(SET_SCANX);   //缩放x
                        s32 y1 = getItemValue(SET_SCANY);   //缩放y
                        float pro = (float)x1/y1;
                        if(item.indexInPara == SET_SCANX)//缩放x
                        {
                           s32 y = (1/pro)*val;
                           setItemValue(SET_SCANY, y);//缩放y
                        }else if(item.indexInPara == SET_SCANY)//缩放y
                        {
                            s32 x = pro*val;
                            setItemValue(SET_SCANX, x);//缩放x
                        };
                    }

                    chgflag = 1;
                    newvalue = val;
                }
            }
        }
        else if (item.valueType == PARA_VALUE_TYPE_SW)    // 开关型
        {
            if (newvalue == 0)
            {
                newvalue = 1;
            }
            else
            {
                newvalue = 0;
            }
            chgflag = 1;
        }
        else if (item.valueType == PARA_VALUE_TYPE_LIST)
        {
            QStringList vallist;
            if(item.selList.indexOf(split2) == -1)
            {  //没找到 二级分割
                vallist = item.selList.split(split1, QString::SkipEmptyParts);
                if (vallist.size() > 0)
                {
                    selIdx = item.selIdx + 1;
                    if (selIdx < 0)
                    {
                        selIdx = 0;
                    }
                    if (selIdx >= vallist.size())   // 循环选择
                    {
                        selIdx = 0;
                    }
                    chgflag = 1;
                }
            }
            else
            {
                //二级分割  注意 key 是 int  val是字符串
                //分清楚 key 并不是 字符串的index  需要区分
                vallist = item.selList.split(split2, QString::SkipEmptyParts);
                if (vallist.size() <= 0)
                {
                    return;
                }
                else
                {
                    // 使用 qmap 组成key: val
                    int miniVal = vallist.first().split(split1, QString::SkipEmptyParts).at(1).toInt();
                    int maxVal  = vallist.last().split(split1, QString::SkipEmptyParts).at(1).toInt();
                    QMap <int,QString> seachDat ;

                    for (int var = 0; var < vallist.size(); ++var)
                    {
                        QStringList mapDatList = vallist.at(var).split(split1, QString::SkipEmptyParts);
                        seachDat.insert(mapDatList.at(1).toInt(),mapDatList.at(0));
                    }

                    selIdx = item.selIdx;

                    if(seachDat.contains(selIdx))
                    {
                        //存在这个key

                    }
                    else
                    {
                        //不存在这个key 用默认值存储
                        selIdx = item.defValue;
                    }

                    //找到下一个val  vallist seach_dat

                    for (int var = 0; var < vallist.size(); ++var)
                    {
                        if( vallist.at(var).split(split1, QString::SkipEmptyParts).at(1).toInt() == selIdx)
                        {
                            var++ ;
                            if( var >= vallist.size())
                            {
                                var = 0 ;
                            }
                            selIdx = vallist.at(var).split(split1, QString::SkipEmptyParts).at(1).toInt();
                            break;
                        }
                    }
                    if (selIdx < miniVal)
                    {
                        selIdx = miniVal;
                    }
                    if (selIdx > maxVal)
                    {
                        selIdx = maxVal;
                    }
                    chgflag = 1;
                }
            }
        }
        else if (item.valueType == PARA_VALUE_TYPE_STRINPUT)    // 字符输入型
        {
            PassWordDialog passWordDlg(this);
            QString str("");
            passWordDlg.setTitleStr(tr("Input"),-1);//输入
            passWordDlg.setShowIfVisible(true);
            int rslt = passWordDlg.exec();
            if(rslt == 1)
            {
                str = passWordDlg.getInputStr();
                if (str != item.valueStr)
                {
                    chgflag = 1;
                    newStrValue = str;
                }
            }
        }
        else if (item.valueType == PARA_VALUE_TYPE_CLICK)    // 点击触发型
        {
            s16 fun = item.indexInPara;
            execItemClickEvent(fun);
            return;
        }

        if (chgflag != 0)
        {
            if(item.valueType == PARA_VALUE_TYPE_LIST)
            {
                m_itemList[itemidx].selIdx = selIdx;
                m_itemList[itemidx].value = selIdx;
            }
            else if(item.valueType == PARA_VALUE_TYPE_STRINPUT)
            {
                m_itemList[itemidx].valueStr = newStrValue;
            }
            else
            {
                m_itemList[itemidx].value = newvalue;//列表里的值等于弹窗输入的值
            }
            //   qDebug()<< " newvalue " << newvalue;
            refreshUi();//在这个函数里刷新
        }
    }
}

//刷新参数值
void ParameterSetDialog::refreshValue()
{
    m_mcParaValues = m_mcParaValues;
    m_wkParaValues = m_wkParaValues;

    for (int i = 0; i < m_itemList.size(); i++)
    {
        int type = m_itemList[i].paraType;
        int idx = m_itemList.at(i).indexInPara;
        int bitInWord = m_itemList[i].bitInWord;
        s32 mcTempValue = m_mcParaValues.buf[idx];
        s32 wkTempValue = m_wkParaValues.buf[idx];

        if (idx < PARA_NUM)
        {
            if (type == PARA_TYPE_MACH)
            {
                // ljs++
                if (bitInWord == 0)
                {
                    m_itemList[i].value = mcTempValue;//列表里的值，变成主控里的值
                    if(m_itemList[i].valueType == PARA_VALUE_TYPE_LIST)
                    {
                        m_itemList[i].selIdx = mcTempValue;
                    }
                }
                else
                {
                    u32 bitval = 0x01;
                    bitval <<= (bitInWord - 1);
                    if ((mcTempValue & bitval) == 0)
                    {
                        m_itemList[i].selIdx = 0;
                        m_itemList[i].value = 0;
                    }
                    else
                    {
                        m_itemList[i].selIdx = 1;
                        m_itemList[i].value = 1;
                    }
                }
            }
            else if (type == PARA_TYPE_WORK)
            {
                // ljs++
                if (bitInWord == 0)
                {
                    m_itemList[i].value = wkTempValue;
                    if(m_itemList[i].valueType == PARA_VALUE_TYPE_LIST)
                    {
                        m_itemList[i].selIdx = wkTempValue;
                    }
                }
                else
                {
                    u32 bitval = 0x01;
                    bitval <<= (bitInWord - 1);
                    if ((wkTempValue & bitval) == 0)
                    {
                        m_itemList[i].selIdx = 0;
                        m_itemList[i].value = 0;
                    }
                    else
                    {
                        m_itemList[i].selIdx = 1;
                        m_itemList[i].value = 1;
                    }
                }
            }
}
    }
}

//收到下位机参数改变信号的槽
void ParameterSetDialog::paraChange(int type, int id)
{
    //点了主板的按钮后，现在这个g_pMachine就是对应主板的
    if (type == SEW_MCPARA_MACH)
    {
        if (id == 0)
        {                                                  //得到当前主板的参数
            memcpy(&m_mcParaValues, &g_pMachine->getMcPara(), sizeof(ParaStruct));

            m_setedFlag |= 0x01;//当前的主板 收到参数包  的标志改变
        }
    }
    else if (type == SEW_MCPARA_WORK)
    {
        if (id == 0)
        {
            memcpy(&m_wkParaValues, &g_pMachine->getWkPara(), sizeof(ParaStruct));
            m_setedFlag |= 0x02;
        }
    }

    m_mcParaValues = m_mcParaValues;
    m_wkParaValues = m_wkParaValues;

    //等于机器参数或工作参数
    if(((m_paraType & PARA_TYPE_MACH) == PARA_TYPE_MACH) ||
            ((m_paraType & PARA_TYPE_WORK) == PARA_TYPE_WORK))
    {
        if (m_setedFlag == 0x03)// = 0x03就是机器参数和主控参数都读过
        {
            if (m_itemList.size() > 0)//参数列表
            {
                ui->buttonOk->setEnabled(true);//如果从下位机得到了数据包，说明与下位机建立了联系。可以点击确认按钮
            }
            refreshValue();
            refreshUi();
        }
    }
}

void ParameterSetDialog::saveParas(int idx)
{
    qDebug()<<"step 1";
    if (m_setedFlag == 0x03 &&
            (m_paraType == (PARA_TYPE_MACH | PARA_TYPE_WORK) ||
             m_paraType == PARA_TYPE_MACH || m_paraType == PARA_TYPE_WORK))
    {
        int size = m_itemList.size();
        if (idx < 0)
        {
            int i;
            for (i = 0; i < size; i++)
            {
                int id = m_itemList.at(i).indexInPara;
                int type = m_itemList.at(i).paraType;
                int bitInWord = m_itemList.at(i).bitInWord;
                int value = m_itemList.at(i).value;
                if (id < PARA_NUM && type == PARA_TYPE_MACH)
                {
                    if (bitInWord == 0)        // ljs++
                    {
                        m_mcParaValues.buf[id] = m_itemList.at(i).value;
                    }
                    else
                    {
                        u32 bitval = 0x01;
                        bitval <<= (bitInWord - 1);
                        if (value == 0)
                        {
                            m_mcParaValues.buf[id] &= ~bitval;
                        }
                        else
                        {
                            m_mcParaValues.buf[id] |= bitval;
                        }
                    }
                }
            }

            qDebug()<<"step 2";
#if(0)
            for(int i = 0; i < MACHINE_NUMBER; i++)
            {
                g_pMachine[i]->setMcPara(&m_mcParaValues);
            }
#endif
            //当前主板的g_pMachine
            g_pMachine->setMcPara(&m_mcParaValues);
            qDebug()<<"step 3";

            for (i = 0; i < size; i++)
            {
                int id = m_itemList.at(i).indexInPara;
                int type = m_itemList.at(i).paraType;
                int bitInWord = m_itemList.at(i).bitInWord;
                int value = m_itemList.at(i).value;
                if (id < PARA_NUM && type == PARA_TYPE_WORK)
                {
                    if (bitInWord == 0)        // ljs++
                    {
                        m_wkParaValues.buf[id] = m_itemList.at(i).value;
                    }
                    else
                    {
                        u32 bitval = 0x01;
                        bitval <<= (bitInWord - 1);
                        if (value == 0)
                        {
                            m_wkParaValues.buf[id] &= ~bitval;
                        }
                        else
                        {
                            m_wkParaValues.buf[id] |= bitval;
                        }
                    }
                }
            }

            qDebug()<<"step 4";
#if(0)
            for(int i = 0; i < MACHINE_NUMBER; i++)
            {
                g_pMachine[i]->setWkPara(&m_wkParaValues);
            }
#endif
            g_pMachine->setWkPara(&m_wkParaValues);
            g_pSettings->writeToIniFile("FlatPanel/WorkPointX", m_wkParaValues.buf[109]);
            g_pSettings->writeToIniFile("FlatPanel/WorkPointY", m_wkParaValues.buf[110]);
            qDebug()<<"step 5";
        }
        else if (idx < size)
        {
            int id = m_itemList.at(idx).indexInPara;
            int type = m_itemList.at(idx).paraType;
            int value = m_itemList.at(idx).value;
            int bitInWord = m_itemList.at(idx).bitInWord;       // ljs++
            if (id < PARA_NUM && type == PARA_TYPE_MACH)
            {
                if (bitInWord == 0)
                {
                    m_mcParaValues.buf[id] = value;
                }
                else
                {
                    u32 bitval = 0x01;
                    bitval <<= (bitInWord - 1);
                    if (value == 0)
                    {
                        m_mcParaValues.buf[id] &= ~bitval;
                    }
                    else
                    {
                        m_mcParaValues.buf[id] |= bitval;
                    }
                    value = m_mcParaValues.buf[id];
                }

                qDebug()<<"step 6";
#if(0)
                for(int i = 0; i < MACHINE_NUMBER; i++)
                {
                    g_pMachine[i]->setAMcPara(id+1, value);
                }
#endif
                g_pMachine->setAMcPara(id+1, value);
                qDebug()<<"step 7";
            }
            else if (id < PARA_NUM && type == PARA_TYPE_WORK)
            {
                if (bitInWord == 0)
                {
                    m_wkParaValues.buf[id] = value;
                }
                else
                {
                    u32 bitval = 0x01;
                    bitval <<= (bitInWord - 1);
                    if (value == 0)
                    {
                        m_wkParaValues.buf[id] &= ~bitval;
                    }
                    else
                    {
                        m_wkParaValues.buf[id] |= bitval;
                    }
                    value = m_wkParaValues.buf[id];
                }

                qDebug()<<"step 8";
#if(0)
                for(int i = 0; i < MACHINE_NUMBER; i++)
                {
                    g_pMachine[i]->setAWkPara(id+1, value);
                }
#endif
                g_pMachine->setAWkPara(id+1, value);
                qDebug()<<"step 9";
            }
        }
    }
}

//执行点击触发型参数的触发事件
void ParameterSetDialog::execItemClickEvent(s16 fun)
{
    g_pMachine->getParasFromMachine();//读取参数

    switch (fun)
    {
    case ROOT_HMICONFIGURATION://进入界面配置
        setMainTitle(tr("HMI Configuration"));
        setSubTitle(tr("Root > HMI Configuration"));
        //得到界面配置列表
        if(g_emDebugMode == nodebugMode)
        {
            if(g_emUser == root)
                setItemList(root,PARA_TYPE_HMICONFIGURATION);//最高权限
        }
        else
        {
            setItemList(root,PARA_TYPE_HMICONFIGURATION);//最高权限
        }
        //设置参数值
        setItemValue(ROOT_RESOLUTION,g_emResolut);   //分辨率
        setItemValue(SET_CONNECTMODE,g_pSettings->readFromIniFile("HMI/connectMode").toInt());
        setItemValue(ROOT_MACTYPE,g_emMacType);  //机器类型
        setItemValue(ROOT_PRODUCTTYPE,g_emProductType);  //产品类型
        setItemValue(ROOT_SHUTTLECHANGE,g_pSettings->readFromIniFile("HMI/shuttleChange").toInt());//自动换梭
        setItemValue(ROOT_WATERMARKSET,g_pSettings->readFromIniFile("HMI/waterMark").toInt());
        setItemValue(ROOT_WIFI,g_pSettings->readFromIniFile("HMI/wifi").toInt());
        setItemValue(ROOT_PARASORTSET,g_pSettings->readFromIniFile("HMI/paraSort").toInt());
        refreshUi();
        break;

    case ROOT_IOTCONFIGURATION: //物联网配置
        setMainTitle(tr("IOT Configuration"));
        setSubTitle(tr("Root > IOT Configuration"));
        // 得到界面配置列表
        setItemList(root,PARA_TYPE_IOTCONFIGURATION);//最高权限
        //设置参数值
        setItemValue(ROOT_GATEWAYCONNECTIONMETHOD,g_pSettings->readFromIniFile("IOT/gatewayConnectMode").toInt()); //网关连接
        setItemValue(ROOT_RACKNUMBERINPUT,g_pSettings->readFromIniFile("IOT/rackNumber").toInt());//机架号
        setItemStr(ROOT_DELIVERYTIME,g_pSettings->readFromIniFile("IOT/deliveryTime").toString()); //工厂预计交货时间
        setItemValue(ROOT_DEBUGPROGRESS,g_pSettings->readFromIniFile("IOT/debugProgress").toInt());//调试进度

        refreshUi();
        break;

    case  ROOT_NETWORKSETTINGS: //网络设置
        setMainTitle(tr("Network Settings"));
        setSubTitle(tr("IOT Configuration > Network Settings"));
        //得到界面配置列表
        //setItemList(factory,PARA_TYPE_NETWORKSETTINGS);

        //设置参数值
        //setItemValue(ROOT_SERVERIPSETTINGS,g_pSettings->readFromIniFile("server/ip").toInt());  //服务器ip设置
        //setItemValue(ROOT_SERVERPORTSETTINGS);

        setGatewayNetworkItemList(PARA_TYPE_NETWORKSETTINGS);

        refreshUi();
        break;

    case ROOT_MACHINEPARA://加载机器参数
        //也用此窗体加载参数
        setMainTitle(tr("Machine parameters"));
        setSubTitle(tr("Root > Machine parameters"));
        //机器参数
        if(g_emUser == root  || g_emDebugMode == debugMode)
        {
            setItemList(g_emUser,PARA_TYPE_MACH);//二级权限  262574
        }
        if(m_setedFlag == 0x03)//如果有从下位机得到过参数包
        {
            refreshValue();//不管连没连上，都显示上次保存的值
        }
        if(g_pMachine->isConnected() == 3)
        {
            if(m_setedFlag != 0x03)//界面上显示已就绪  但是没有从下位机得到过参数包（刚上电时）
            {
                PromptDialog dlg(this);
                dlg.initDialog(PromptDialog::BTN_OK);
                dlg.setTitleStr(tr("Network error"));
                dlg.setContentStr(tr("read parameter..."));//读取参数中...
                dlg.exec();
            }
        }
        else
        {
#ifdef Q_OS_LINUX//为了方便windows下查看参数所以加了linux编译条件
            PromptDialog dlg(this);
            dlg.initDialog(PromptDialog::BTN_OK);
            dlg.setTitleStr(tr("Network error"));
            dlg.setContentStr(tr("No connection"));
            dlg.exec();
            done(0);
#endif
        }
        refreshUi();
        break;

    case ROOT_WORKPARA://加载工作参数
        //也用此窗体加载参数
        setMainTitle(tr("Work parameters"));
        setSubTitle(tr("Root > Work parameters"));
        //工作参数
        if(g_emUser == root || g_emDebugMode == debugMode)
        {
            setItemList(root,PARA_TYPE_WORK);//二级权限  262574
        }

        if(m_setedFlag == 0x03)//如果有从下位机得到过参数包
        {
            refreshValue();//不管连没连上，都显示上次保存的值
        }
        if(g_pMachine->isConnected() == 3)
        {
            if(m_setedFlag != 0x03)//界面上显示已就绪  但是没有从下位机得到过参数包（刚上电时）
            {
                PromptDialog dlg(this);
                dlg.initDialog(PromptDialog::BTN_OK);
                dlg.setTitleStr(tr("Network error"));
                dlg.setContentStr(tr("read parameter..."));//读取参数中...
                dlg.exec();
            }
        }
        else
        {
#ifdef Q_OS_LINUX//为了方便windows下查看参数所以加了linux编译条件
            PromptDialog dlg(this);
            dlg.initDialog(PromptDialog::BTN_OK);
            dlg.setTitleStr(tr("Network error"));
            dlg.setContentStr(tr("No connection"));
            dlg.exec();
            done(0);
#endif
        }
        refreshUi();
        break;

    case ROOT_HMIDECRYPT://界面解密
        emit siHMIDecrypt(m_networkCardID);
        break;

    case ROOT_CLEARPATTERN://花样总清
        emit siPatternClear();
        break;

    case ROOT_CHANGEPASSWORD://修改一级密码
        emit siChangePassword();
        break;

    case ROOT_DELETEINI://删除配置文件
        emit siDeleteIni();//删除执行目录下的config
        break;

    case ROOT_DEBUGMODE://界面进入调试模式
        emit siDebugMode();
        break;

    case PSE_SOFTWAREPARA_IMPORTPARA://参数导入
        emit siParameterImport();
        break;

    case PSE_SOFTWAREPARA_EXPORTPARA://参数导出
        emit siParameterExport();
        break;

    case PSE_SOFTWAREPARA_HMIUPDATE://界面升级
        emit siHMIUpgrade();
        break;

    case PSE_SOFTWAREPARA_MCUPDATE://主控升级
        emit siMCUpgrade();
        break;
    case PSE_SOFTWAREPARA_EXIT://退出程序
        emit siExit();
        break;
    default:
        break;
    }
}

void ParameterSetDialog::initData()
{
    m_curPage = 0;
    m_rootCurPage = 0;
    m_paraType = 0;    //参数类型(机器参数、工作参数、花样参数等)
    m_paraTypeSort = 0;   //参数类型分类型(动作参数、位置参数、亮片参数等)
    m_itemList.clear();
    m_allItemList.clear();

    if (m_setedFlag == 0)
    {
        memset(m_mcParaValues.buf, 0, sizeof(ParaStruct));
        memset(m_wkParaValues.buf, 0, sizeof(ParaStruct));
    }

    m_filePath.clear();
}

//设置类型图标
void ParameterSetDialog::setTypeLogo(QString tStyle)
{
    ui->buttonTypeLogo->setUnPreBtnLogo(tStyle);
}

//设置主title
void ParameterSetDialog::setMainTitle(QString str)
{
    ui->labelMainTitle->setText(str);
}

//设置副title
void ParameterSetDialog::setSubTitle(QString str)
{
    ui->labelSubTitle->setText(str);
}

//(参数权限、参数类型、参数种类)得到相应参数类型列表
// sort参数分类的小分类
void ParameterSetDialog::setItemList(int authority,int64_t type,int64_t sort)
{
    m_paraType = type;
    m_paraTypeSort = sort;
    m_itemList.clear();//最后筛选出的列表

    //参数筛选
    for(int i = 0; i < m_allItemList.size(); i++)
    {
        int aType= m_allItemList.at(i).paraType;
        int aAuthority = m_allItemList.at(i).authority;

        if((aType & type) == aType)
        {
            int aSort= m_allItemList.at(i).paraTypeSort;
            if(sort == -1)//等于-1加载全部
            {
                //外边传进来的权限 root 加载所有
                if(authority == root)
                {
                    m_itemList.append(m_allItemList.at(i));
                }
                else
                { //当前列表里的权限  等于  传进来的权限
                    if(aAuthority <= authority)//参数权限
                    {
                        m_itemList.append(m_allItemList.at(i));
                    }
                }
            }
            else
            {
                if((aSort & sort)== sort)//参数类型
                {
                    if(authority == root)//最高参数权限
                    {
                        m_itemList.append(m_allItemList.at(i));
                    }
                    else
                    {
                        if(aAuthority <= authority)//参数权限
                        {
                            m_itemList.append(m_allItemList.at(i));
                        }
                    }
                }
            }
        }
    }
}

void ParameterSetDialog::refreshProductType()
{
    int mcType = 0;
    for(int i = 0; i < m_itemList.size(); i++)
    {
        if(m_itemList[i].indexInPara == ROOT_MACTYPE)
        {
            mcType = m_itemList[i].selIdx;
            break;
        }
    }

    for(int i = 0; i < m_itemList.size(); i++)
    {
        int index = m_itemList.at(i).indexInPara;

        if(index == ROOT_PRODUCTTYPE)//等于产品类型
        {
            switch (mcType) //机器类型
            {

            case 0:
                break;

            default://其他机型
                g_emProductType = PRODUCT_NULL;
                m_itemList[i].minVal = PRODUCT_NULL;
                m_itemList[i].maxVal = PRODUCT_NULL;
                m_itemList[i].value = PRODUCT_NULL;
                m_itemList[i].selIdx = g_emProductType;
                break;
            }
            break;
        }
    }
}

//设置网关网络参数(IP和端口)
void ParameterSetDialog::setGatewayNetworkItemList(int64_t type)
{
    m_paraType = type;
    m_itemList.clear();

    QDir apppath(qApp->applicationDirPath());
    QString serverip, localip;
    quint16  serverport, localport;
    //服务器IP及端口设置
    int idx = 0;
    QString  configfile;
    configfile = apppath.path() + apppath.separator() + "lotconfig.ini";
    QSettings configIni(configfile, QSettings::IniFormat);

    serverip = configIni.value("server/ip", QVariant("8.130.165.100")).toString();
    ParaItem slpItem;
    slpItem.indexInPara = idx;
    slpItem.readonly = 0;
    slpItem.valueType = PARA_VALUE_TYPE_STRINPUT;
    slpItem.paraName = tr("Server IP  settings"); //服务器IP设置;
    slpItem.valueStr = serverip;
    m_itemList.append(slpItem);

    serverport = configIni.value("server/port", QVariant(9014)).toInt();
    idx++;
    ParaItem sPortItem;
    sPortItem.indexInPara = idx;
    sPortItem.readonly = 0;
    sPortItem.valueType = PARA_VALUE_TYPE_INT;
    sPortItem.paraName = tr("Server Port settings") ;//服务器端口设置
    sPortItem.value = serverport;
    sPortItem.minVal = 0;
    sPortItem.maxVal = U16_MAX;
    sPortItem.defValue = serverport;
    m_itemList.append(sPortItem);

    //本地IP设置条目
    localip = configIni.value("local/ip", QVariant("192.168.110.79")).toString();
    idx ++;
    ParaItem lIpItem;
    lIpItem.indexInPara = idx;
    lIpItem.readonly = 0;
    lIpItem.valueType = PARA_VALUE_TYPE_STRINPUT;
    lIpItem.paraName = tr("Local IP settings");//本地IP设置
    lIpItem.valueStr = localip;
    m_itemList.append(lIpItem);

    localport = configIni.value("local/port", QVariant(5000)).toInt();
    idx++;
    ParaItem lPortItem;
    lPortItem.indexInPara = idx;
    lPortItem.readonly = 0;
    lPortItem.valueType = PARA_VALUE_TYPE_INT;
    lPortItem.paraName = tr("Local Port  settings");//本口端口设置
    lPortItem.value = localport;
    lPortItem.minVal = 0;
    lPortItem.maxVal = U16_MAX;
    lPortItem.defValue = localport;
    m_itemList.append(lPortItem);
}

//设置网络参数(IP和端口)
void ParameterSetDialog::setNetworkItemList(int64_t type)
{
    m_paraType = type;
    m_itemList.clear();

    QDir apppath(qApp->applicationDirPath());
    QString serverip,localip;
    quint16 serverport,localport;
    //服务器IP及端口设置条目(包括网关)
    int idx = 0;
    QString configfile;
    configfile = apppath.path() + apppath.separator() + "mcconfig.ini";//读取的配置文件名字
    QSettings configIni(configfile, QSettings::IniFormat);
    serverip = configIni.value("server/ip", QVariant("192.168.16.253")).toString();//把配置文件里的号转换成字符串
    localip = configIni.value("local/ip", QVariant("192.168.16.41")).toString();

    ParaItem sIpItem;
    sIpItem.indexInPara = idx;
    sIpItem.readonly = 0;
    sIpItem.valueType = PARA_VALUE_TYPE_STRINPUT;
    sIpItem.paraName = tr("Board IP settings");//主板IP设置
    sIpItem.valueStr = serverip;//列表里的值就显示从配置文件读上来的
    m_itemList.append(sIpItem);//把这行加到列表里

    serverport = configIni.value("server/port", QVariant(5000)).toInt();
    idx++;
    ParaItem sPortItem;
    sPortItem.indexInPara = idx;
    sPortItem.readonly = 0;
    sPortItem.valueType = PARA_VALUE_TYPE_INT;
    sPortItem.paraName = tr("Board port settings");//主板端口设置
    sPortItem.value = serverport;
    sPortItem.minVal = 0;
    sPortItem.maxVal = U16_MAX;
    sPortItem.defValue = serverport;
    m_itemList.append(sPortItem);

    idx++;

    //本地IP设置条目
    ParaItem lIpItem;
    lIpItem.indexInPara = idx;
    lIpItem.readonly = 0;
    lIpItem.valueType = PARA_VALUE_TYPE_STRINPUT;
    lIpItem.paraName = tr("Local IP settings");//本地IP设置
    lIpItem.valueStr = localip;
    m_itemList.append(lIpItem);
    idx++;

    //本地端口设置条目
    localport = configIni.value("local/port", QVariant(5000)).toInt();

    ParaItem lPortItem;
    lPortItem.indexInPara = idx;
    lPortItem.readonly = 0;
    lPortItem.valueType = PARA_VALUE_TYPE_INT;
    lPortItem.paraName = tr("Local port settings");//本地端口设置
    lPortItem.value = localport;
    lPortItem.minVal = 0;
    lPortItem.maxVal = U16_MAX;
    lPortItem.defValue = 5000;
    m_itemList.append(lPortItem);
}

void ParameterSetDialog::setCurPage(int idx)
{
    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        m_rootCurPage = idx;
    }
    else
    {
        m_curPage = idx;
    }
}

//设置参数值
void ParameterSetDialog::setItemValue(int idx,int value)
{
    //筛选参数
    for(int i = 0; i < m_itemList.size(); i++)
    {
        int index = m_itemList.at(i).indexInPara;
        int min = m_itemList.at(i).minVal;
        int max = m_itemList.at(i).maxVal;

        if(idx == index)//参数枚举
        {
            if(value > max || value < min) //
            {
                value = m_itemList.at(i).defValue;
            }
            m_itemList[i].selIdx = value;
            m_itemList[i].value = value;
        }
    }
}

void ParameterSetDialog::setItemStr(int idx, QString str)
{
    for(int i = 0; i < m_itemList.size(); i++)
    {
        int index = m_itemList.at(i).indexInPara;

        if(idx == index)
        {
            m_itemList[i].valueStr = str;
        }
    }
}

int ParameterSetDialog::getItemValue(int idx)
{
    int value = 0;
    for(int i = 0; i < m_itemList.size(); i++)
    {
        if(idx == m_itemList.at(i).indexInPara)
        {
            value = m_itemList.at(i).value;
        }
    }
    return value;
}

int ParameterSetDialog::exec()
{
    //等于机器参数或工作参数
    if(((m_paraType & PARA_TYPE_MACH) == PARA_TYPE_MACH) ||
            ((m_paraType & PARA_TYPE_WORK) == PARA_TYPE_WORK))
    {
        if (g_pMachine != NULL)
        {
            qDebug("send GetParasFromMachine");

            if(m_setedFlag == 0x03)//如果有从下位机得到过参数包
            {
                //这个函数会把从主控得到的参数保存在item.value里
                refreshValue();//不管连没连上，都显示上次保存的值，多主板保存各自主板的值
            }

            if(g_pMachine->isConnected() == 3)//这个isConnected检测机制是5秒
            {
                if(((m_paraType & PARA_TYPE_MACH) == PARA_TYPE_MACH) ||
                        ((m_paraType & PARA_TYPE_WORK) == PARA_TYPE_WORK))
                {
                    // 多主板的之前就设置好了g_pMachine   点哪个按钮，就用向哪个主板获取参数
                    g_pMachine->getParasFromMachine();//如果连上了主板，发送一个读取参数信息的包
                }
                if(m_setedFlag != 0x03)//界面上显示已就绪  但是没有从下位机得到过参数包（刚上电时）
                {
                    PromptDialog dlg(this);
                    dlg.initDialog(PromptDialog::BTN_OK);
                    dlg.setTitleStr(tr("Network error"));
                    dlg.setContentStr(tr("read parameter..."));//读取参数中...
                    dlg.exec();
                    return -1;
                }
            }
            else//如果没连接上
            {
                if((g_emMacType == MACHINE_FLYFLATCUTTING)
                        && (g_emDebugMode == nodebugMode)){
                    PromptDialog dlg(this);
                    dlg.initDialog(PromptDialog::BTN_OK);
                    dlg.setTitleStr(tr("Network error"));
                    dlg.setContentStr(tr("No connection"));
                    dlg.exec();
                    return -1;
                }
#ifdef Q_OS_LINUX//为了方便windows下查看参数所以加了linux编译条件
                PromptDialog dlg(this);
                dlg.initDialog(PromptDialog::BTN_OK);
                dlg.setTitleStr(tr("Network error"));
                dlg.setContentStr(tr("No connection"));
                dlg.exec();
                return -1;
                //不进行下边的函数
#endif
            }
        }
    }
    //刷新这个函数，就显示item.value的值
    //ui->buttonOk->setEnabled(false);
    refreshUi();//没连接主板的时候就先进到这个函数,就会显示的默认参数
    return QDialog::exec();
}

int ParameterSetDialog::addParaItem(const QList<ParaItem> &itemList)
{
    int size = m_allItemList.size();
    m_allItemList.append(itemList);
    return size;
}

int ParameterSetDialog::addParaItem(const ParaItem &item)
{
    int size = m_allItemList.size();
    m_allItemList.append(item);
    return size;
}

void ParameterSetDialog::on_button1_clicked()
{
    changeValue(0);
}

void ParameterSetDialog::on_button2_clicked()
{
    changeValue(1);
}

void ParameterSetDialog::on_button3_clicked()
{
    changeValue(2);
}

void ParameterSetDialog::on_button4_clicked()
{
    changeValue(3);
}

void ParameterSetDialog::on_button5_clicked()
{
    changeValue(4);
}

void ParameterSetDialog::on_button6_clicked()
{
    changeValue(5);
}

void ParameterSetDialog::on_button7_clicked()
{
    changeValue(6);
}

void ParameterSetDialog::on_button8_clicked()
{
    changeValue(7);
}

void ParameterSetDialog::on_button9_clicked()
{
    changeValue(8);
}

void ParameterSetDialog::on_button10_clicked()
{
    changeValue(9);
}

void ParameterSetDialog::on_button11_clicked()
{
    changeValue(10);
}

void ParameterSetDialog::on_button12_clicked()
{
    changeValue(11);
}

void ParameterSetDialog::on_buttonPgUp_clicked()
{
    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        m_rootCurPage--;
    }
    else
    {
        m_curPage--;
    }

    refreshUi();
}

void ParameterSetDialog::on_buttonPgDn_clicked()
{
    if(m_paraType == PARA_TYPE_ROOT)//等于超级用户界面
    {
        m_rootCurPage++;
    }
    else
    {
        m_curPage++;
    }
    refreshUi();
}

void ParameterSetDialog::on_buttonOk_clicked()
{
    PromptDialog promptDlg(this);
    qDebug()<<"para ok 1";

    //等于机器参数或工作参数
    if(((m_paraType & PARA_TYPE_MACH) == PARA_TYPE_MACH) ||
            ((m_paraType & PARA_TYPE_WORK) == PARA_TYPE_WORK))
    {
        qDebug()<<"para ok 4";
        saveParas();
    }

    //等于软件设置参数
    if((m_paraType & PARA_TYPE_SOFTWARESET) == PARA_TYPE_SOFTWARESET)
    {
        qDebug()<<"para ok 5";

        promptDlg.initDialog(PromptDialog::BTN_OK_CANCEL);
        promptDlg.setTitleStr(tr("Prompt"));

        QString str;
        str = tr("The settings take effect after restarting the interface!");//重启界面后设置生效!
        promptDlg.setContentStr(str);
        if(promptDlg.exec() == 1)
        {
//            g_emTheme = (Theme)(m_itemList.at((s16)SET_THEME).value);//主题
            int language = m_itemList.at((s16)SET_LANGUAGE).value;
            g_pSettings->writeToIniFile("HMI/language",language);

            g_pSettings->writeToIniFile("HMI/FrontSize",m_itemList.at((s16)SET_FONTSIZE).value);
#ifdef Q_OS_WIN            
            qApp->exit();
#endif

#ifdef Q_OS_LINUX
            qDebug()<<"reboot before";
            system("reboot");
            qDebug()<<"reboot end";
#endif
        }

        qDebug()<<"para ok 6";
        return;
    }

    //等于网络管理参数
    if((m_paraType & PARA_TYPE_NETWORKSET) == PARA_TYPE_NETWORKSET)
    {
        qDebug()<<"para ok 7";

        //网络设置完成,需重启后重新建立连接
        promptDlg.initDialog(PromptDialog::BTN_OK_CANCEL);
        QString str = tr("Network settings are completed, re-establish after reboot");
        promptDlg.setTitleStr(tr("Prompt"));
        promptDlg.setContentStr(str);
        if(promptDlg.exec() == 1)
        {
            QDir apppath(qApp->applicationDirPath());

            s16 idx = 0;//参数索引
            QString configfile;
            configfile = apppath.path() + apppath.separator() + "mcconfig.ini";
            QSettings configIni(configfile, QSettings::IniFormat);

            QString serverip = m_itemList.at(idx).valueStr;//服务器IP
            idx++;
            int serverport = m_itemList.at(idx).value;//服务器端口

            // 回写参数
            configIni.setValue("server/ip", serverip);
            configIni.setValue("server/port", serverport);

            idx++;

            QString localip = m_itemList.at(idx).valueStr;//本地IP
            // 回写参数
            configIni.setValue("local/ip", localip);

            idx++;

            int localport = m_itemList.at(idx).value;//本地端口
            // 回写参数
            configIni.setValue("local/port", localport);

#ifdef Q_OS_WIN
            qApp->exit();
#endif

#ifdef Q_OS_LINUX
            system("reboot");
#endif
        }
        return;
    }

    //等于网关网络设置参数
    if((m_paraType & PARA_TYPE_NETWORKSETTINGS) == PARA_TYPE_NETWORKSETTINGS)
    {
        //网络设置完成,需重启后重新建立连接
        promptDlg.initDialog(PromptDialog::BTN_OK_CANCEL);
        QString str = tr("Network settings are completed, re-establish after reboot");
        promptDlg.setTitleStr(tr("Prompt"));
        promptDlg.setContentStr(str);
        if(promptDlg.exec() == 1)
        {
            QDir apppath(qApp->applicationDirPath());

            s16 idx =0; //参数索引
            QString  configfile;
            configfile = apppath.path() + apppath.separator() +"lotconfig.ini";
            QSettings configIni(configfile, QSettings::IniFormat);

            QString serverip = m_itemList.at(idx).valueStr;//服务器IP
            idx++;
            int serverport = m_itemList.at(idx).value;//服务器端口
            idx++;
            QString localip = m_itemList.at(idx).valueStr;//本地IP
            idx++;
            int localport = m_itemList.at(idx).value;//本地端口

            // 回写参数
            configIni.setValue("server/ip", serverip);
            configIni.setValue("server/port", serverport);
            configIni.setValue("local/ip", localip);
            configIni.setValue("local/port", localport);

#ifdef Q_OS_WIN
            qApp->exit();
#endif

#ifdef Q_OS_LINUX
            system("reboot");
#endif
        }
        return;
    }

    //等于时间设置参数
    if((m_paraType & PARA_TYPE_TIMESET) == PARA_TYPE_TIMESET)
    {
        int yearValue = m_itemList.at(0).value;
        int monthValue = m_itemList.at(1).value;
        int dayValue = m_itemList.at(2).value;

#ifdef Q_OS_LINUX
        int hourValue = m_itemList.at(3).value;
        int minuteValue = m_itemList.at(4).value;
        int secondValue = m_itemList.at(5).value;
#endif

        int temp = 0;

        //判断是否为闰年，闰年2月份是29天，其他是28天
        if((yearValue % 4 == 0) && (yearValue % 100 != 0))
        {
            if(monthValue == 2)
            {
                if(dayValue > 29)
                {
                    temp = -1;
                }
            }
        }
        else
        {
            if(monthValue == 2)
            {
                if(dayValue > 28)
                {
                    temp = -1;
                }
            }
        }

        //1、3、5、7、8、10、12是31天，其他是30天
        if(monthValue == 4 || monthValue == 6 || monthValue == 9 || monthValue == 11)
        {
            if(dayValue > 30)
            {
                temp = -1;
            }
        }

        QString  showStr;
        if(temp == 0)
        {
            //设置时间
#ifdef Q_OS_LINUX
            struct tm rtcTime;
            rtcTime.tm_year = yearValue - 1900;
            rtcTime.tm_mon = monthValue - 1;
            rtcTime.tm_mday = dayValue;
            rtcTime.tm_hour = hourValue;
            rtcTime.tm_min = minuteValue;
            rtcTime.tm_sec = secondValue;
            rtcTime.tm_isdst = 0;
            rtcTime.tm_yday = 0;
            rtcTime.tm_wday = 0;

            int retval = hal_set_rtc_time(&rtcTime);
            if(retval != 0)
            {
                qDebug("set_rtc_time failed: %d!", retval);
                temp = -2;
            }
#endif
            //时间设置完成,重启后生效
            promptDlg.initDialog(PromptDialog::BTN_RESTART);
            showStr = tr("The time setting is completed and will take effect after restart");
        }
        else if(temp == -1)
        {
            //时间设置不合理,请重新设置
            promptDlg.initDialog(PromptDialog::BTN_OK);
            showStr = tr("Unreasonable time setting, please reset");
        }

        if(temp == -2)
        {
            //时间设置失败,请重新设置
            promptDlg.initDialog(PromptDialog::BTN_OK);
            showStr = tr("Time setting failed, please reset");
        }

        promptDlg.setTitleStr(tr("Prompt"));
        promptDlg.setContentStr(showStr);
        promptDlg.exec();
        return;
    }

    //等于超级用户界面配置参数
    if((m_paraType & PARA_TYPE_HMICONFIGURATION) == PARA_TYPE_HMICONFIGURATION)
    {
        qDebug()<<"para ok 5";

        promptDlg.initDialog(PromptDialog::BTN_OK_CANCEL);
        promptDlg.setTitleStr(tr("Prompt"));

        QString str;
        str = tr("The settings take effect after restarting the interface!");//重启界面后设置生效!
        promptDlg.setContentStr(str);
        if(promptDlg.exec() == 1)
        {
            //重置初始花样
            g_pSettings->writeToIniFile("Pattern/name","");
            //界面配置里的参数都放在了 点击触发型参数枚举 里,要筛选才能获取到相应的value值
            for(int i = 0; i < m_itemList.size(); i++)
            {
                if(m_itemList[i].indexInPara == ROOT_RESOLUTION)
                {
                    g_emResolut = (Resolution)(m_itemList[i].value);//分辨率
                    g_pSettings->writeToIniFile("HMI/resolution",g_emResolut);
                }
                else if (m_itemList[i].indexInPara == SET_CONNECTMODE)
                {
                    int connectMode = (s16)m_itemList[i].value;//连接通讯方式
                    g_pSettings->writeToIniFile("HMI/connectMode",connectMode);
                }

                else if(m_itemList[i].indexInPara == ROOT_PRODUCTTYPE)
                {
                    g_emProductType =(ProductType)(m_itemList[i].value);//产品类型
                    g_pSettings->writeToIniFile("HMI/productType",g_emProductType);
                }

                else if(m_itemList[i].indexInPara == ROOT_SHUTTLECHANGE)
                {
                    s16 shuttleChange =(s16)(m_itemList[i].value);//自动换梭
                    g_pSettings->writeToIniFile("HMI/shuttleChange",shuttleChange);
                }

                else if(m_itemList[i].indexInPara == ROOT_WATERMARKSET)
                {
                    s16 waterMark =(s16)(m_itemList[i].value);//主背景是否带水印
                    g_pSettings->writeToIniFile("HMI/waterMark",waterMark);
                }
                else if(m_itemList[i].indexInPara == ROOT_WIFI)
                {
                    s16 wifi =(s16)(m_itemList[i].value);//是否带wifi
                    g_pSettings->writeToIniFile("HMI/wifi",wifi);
                }

                else if(m_itemList[i].indexInPara == ROOT_PARASORTSET)
                {
                    s16 paraSort =(s16)(m_itemList[i].value);//参数是否分类显示
                    g_pSettings->writeToIniFile("HMI/paraSort",paraSort);
                }
                else if(m_itemList[i].indexInPara == ROOT_MACTYPE)
                {
                    g_emMacType = (MachineType)(m_itemList[i].value);//机器类型
                    g_pSettings->writeToIniFile("HMI/machineType",g_emMacType);
                }
}

#ifdef Q_OS_WIN
            qApp->exit();
#endif

#ifdef Q_OS_LINUX
            system("reboot");
#endif
        }
        return;
    }

    //等于超级用户物联网配置参数
    if((m_paraType & PARA_TYPE_IOTCONFIGURATION) == PARA_TYPE_IOTCONFIGURATION)
    {
        qDebug()<<"para ok 66";

        for(int i = 0; i<m_itemList.size();  i++)
        {
            if(m_itemList[i].indexInPara == ROOT_RACKNUMBERINPUT)
            {
                int RackNumber = m_itemList[i].value;//机架号
                g_pSettings->writeToIniFile("IOT/rackNumber",RackNumber);
            }
            else if(m_itemList[i].indexInPara == ROOT_DELIVERYTIME)
            {
                QString deliveryTime = m_itemList[i].valueStr;//工厂预计交货时间
                g_pSettings->writeToIniFile("IOT/deliveryTime",deliveryTime);
            }
            else if(m_itemList[i].indexInPara == ROOT_DEBUGPROGRESS)
            {
                int debugProgress = m_itemList[i].value;//调试进度
                g_pSettings->writeToIniFile("IOT/debugProgress",debugProgress);
            }
        }

        //网关连接方式改变时需要提示重启
        s16 cFlag = 0;
        for(int i = 0; i<m_itemList.size();  i++)
        {
            if(m_itemList[i].indexInPara == ROOT_GATEWAYCONNECTIONMETHOD)
            {
                int bVal = g_pSettings->readFromIniFile("IOT/gatewayConnectMode").toInt();
                int eVal = m_itemList[i].value;//网关连接方式
                if(bVal != eVal)
                {
                    cFlag = 1;
                }
                break;
            }
        }

        if(cFlag == 1)
        {
            promptDlg.initDialog(PromptDialog::BTN_OK_CANCEL);
            promptDlg.setTitleStr(tr("Prompt"));
            QString str;
            str = tr("Connection mode changes, take effect after the reboot!");//连接方式改变，重启界面后生效!
            promptDlg.setContentStr(str);
            if(promptDlg.exec() == 1)
            {
                for(int i = 0; i<m_itemList.size();  i++)
                {
                    if(m_itemList[i].indexInPara == ROOT_GATEWAYCONNECTIONMETHOD)
                    {
                        int gatewayConnect = m_itemList[i].value;//网关连接方式
                        g_pSettings->writeToIniFile("IOT/gatewayConnectMode",gatewayConnect);
                        break;
                    }
                }

#ifdef Q_OS_WIN
                qApp->exit();
#endif

#ifdef Q_OS_LINUX
                system("reboot");
#endif
            }
            return;
        }
        else
        {
            done(1);
        }
    }
    //超级用户密码权限,单次有效
//    g_emUser = operate;
    done(1);//0是关掉

    qDebug()<<"para ok 8";

}

void ParameterSetDialog::on_buttonCancel_clicked()
{
    //超级用户密码权限,单次有效
//    g_emUser = operate;
    done(0);
}

//恢复默认的参数
void ParameterSetDialog::on_buttonParaRestore_clicked()
{
    if(g_emDebugMode == nodebugMode)
    {
        if(g_emUser != resetpara)//权限不够先登录
        {
            emit siUserLogin(resetpara);
            if(g_emUser != resetpara)//发送登录信号后，权限如果还没改变就返回
            {
                return;
            }
        }
        PromptDialog promptDlg(this);
        promptDlg.initDialog(PromptDialog::BTN_OK_CANCEL);
        promptDlg.setTitleStr(tr("Prompt"));

        if(m_paraType == PARA_TYPE_MACH ||
                m_paraType == PARA_TYPE_WORK)
        {
            promptDlg.setContentStr(tr("Whether to recover the default parameters for the board?"));//是否恢复为主板默认参数?
        }

        if(promptDlg.exec() == 1)
        {
            if(g_pMachine != NULL)
            {
              if(m_paraType == PARA_TYPE_MACH ||
                        m_paraType == PARA_TYPE_WORK)//设置主板默认参数
                {
                    g_pMachine->setToDefaultParas(UCMD_SET_DEF_PARA, 0);
                }
            }
        }
    }
    g_emUser = operate;
}

//返回上一级菜单
void ParameterSetDialog::on_buttonReturn_clicked()
{
    if(g_emDebugMode == nodebugMode)
    {
        if(g_emUser == root)
        {
            setMainTitle(tr("Root"));
            setSubTitle(tr("Accessibility > Root"));
            //超级用户参数
            setItemList(g_emUser,PARA_TYPE_ROOT);
            refreshUi();
        }
    }
    else
    {
        setMainTitle(tr("Root"));
        setSubTitle(tr("Accessibility > Root"));
        //超级用户参数
        setItemList(root,PARA_TYPE_ROOT);
        refreshUi();
    }
}
